package com.gyg.executorDemo;


/**
 * 多个线程同时操作同一个对象
 */
public class TestThread04 implements Runnable {

    private static String winner;

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {

            System.out.println(Thread.currentThread().getName() + "--->走了" + i + "步");
            boolean isGameOver = gameOver(i);
            if (isGameOver) {
                break;
            }
            //模拟兔子睡觉
            if (Thread.currentThread().getName().equals("兔子") && i % 80 == 0) {
                try {
                    System.out.println(Thread.currentThread().getName() + "正在睡觉**********");
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 判断游戏结束
     *
     * @param i
     * @return
     */
    private boolean gameOver(int i) {
        if (winner != null) {
            return true;
        }
        if (i == 100) {
            System.out.println("winner is " + Thread.currentThread().getName());
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        TestThread04 thread04 = new TestThread04();
        new Thread(thread04, "兔子").start();
        new Thread(thread04, "乌龟").start();
    }
}
